package org.video.mine.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.video.mine.GlobalStr;
import org.video.mine.MyPreference;
import org.video.mine.R;
import org.video.mine.adapter.LoadingAdapter;
import org.video.mine.databinding.ActivityVideoLoadBinding;
import org.video.mine.entity.AlreadyLoadOkEntity;
import org.video.mine.entity.LoadedEntity;
import org.video.mine.entity.LoadingEntity;
import org.video.mine.event.DeleteFileEvent;
import org.video.mine.event.DownLoadOkEvent;
import org.video.mine.event.UpdataLoadActivity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class VideoLoadActivity extends AppCompatActivity {

    private ActivityVideoLoadBinding binding;
    private List<LoadedEntity> loadedEntities = new ArrayList<>();
    private List<LoadedEntity> loadingEntities = new ArrayList<>();
    private Context context;
    private LoadingAdapter loadedAdapter;
    private LoadingAdapter loadingAdapter;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 0:
                    if (loadedEntities==null || loadedEntities.size()==0){
                        binding.llLoaded.setVisibility(View.GONE);
                    }else {
                        binding.llLoaded.setVisibility(View.VISIBLE);
                    }
                    if (loadingEntities==null || loadingEntities.size()==0){
                        binding.llLoading.setVisibility(View.GONE);
                    }else {
                        binding.llLoading.setVisibility(View.VISIBLE);
                    }
                    loadedAdapter.notifyDataSetChanged();
                    loadingAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };
    private MyPreference preference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_video_load);
        setContentView(binding.getRoot());
        context = this;
        EventBus.getDefault().register(this);

        initView();
        initData();
    }

    private void initView() {
        LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
        layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        binding.recycleLoaded.setLayoutManager(layoutManager1);
        loadedAdapter = new LoadingAdapter(loadedEntities, context,false);
        binding.recycleLoaded.setAdapter(loadedAdapter);

        LinearLayoutManager layoutManager2 = new LinearLayoutManager(this);
        layoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
        binding.recycleLoading.setLayoutManager(layoutManager2);
        loadingAdapter = new LoadingAdapter(loadingEntities, context,true);
        binding.recycleLoading.setAdapter(loadingAdapter);

        preference = MyPreference.getInstance();
        preference.setPreference(context);

        binding.rlLoaded.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (binding.recycleLoaded.getVisibility()==View.VISIBLE){
                    binding.recycleLoaded.setVisibility(View.GONE);
                    binding.ivLoaded.setImageResource(R.drawable.up);
                }else {
                    binding.recycleLoaded.setVisibility(View.VISIBLE);
                    binding.ivLoaded.setImageResource(R.drawable.down);
                }
            }
        });
        binding.rlLoading.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (binding.recycleLoading.getVisibility()==View.VISIBLE){
                    binding.recycleLoading.setVisibility(View.GONE);
                    binding.ivLoading.setImageResource(R.drawable.up);
                }else {
                    binding.recycleLoading.setVisibility(View.VISIBLE);
                    binding.ivLoading.setImageResource(R.drawable.down);
                }
            }
        });
    }

    private void initData() {
        loadingEntities.clear();
        loadedEntities.clear();
        File file = new File(GlobalStr.getSDPath(context));
        if (file.exists()){
            for (File f : file.listFiles()) {
                if (f.isDirectory()){
                    int fileCount = 0;
                    LoadedEntity loadedEntity = new LoadedEntity();
                    loadedEntity.setName(f.getName());
                    loadedEntity.setImgUrl(isHaveLoadok(f.getName()));
                    loadedEntity.setFileDir(f.getAbsolutePath());
                    long size = 0;
                    for (File f1:f.listFiles()){
                        if (f1.isDirectory()){
                            if (f1.listFiles().length==0){
                                f1.delete();
                            }
                        }else {
                            try {
                                fileCount++;
                                FileInputStream fileInputStream = new FileInputStream(f1);
                                int size1 = fileInputStream.available();
                                size = size+size1;
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    loadedEntity.setSize(GlobalStr.formetFileSize(size));
                    loadedEntity.setCount(fileCount);
                    if (fileCount>0) {
                        loadedEntities.add(loadedEntity);
                    }else {
                        List<AlreadyLoadOkEntity> getLoaded = (List<AlreadyLoadOkEntity>) preference.getObject(MyPreference.loadok, AlreadyLoadOkEntity.class);
                        if (getLoaded!=null && getLoaded.size()>0) {
                            for (AlreadyLoadOkEntity loadingEntity : getLoaded) {
                                if (loadingEntity.getName().equals(f.getName())){
                                    getLoaded.remove(loadingEntity);
                                    preference.setObject(MyPreference.loadok,getLoaded);
                                    break;
                                }
                            }
                        }
                        f.delete();
                    }
                }
            }
        }
        List<LoadingEntity> getLoading = (List<LoadingEntity>) preference.getObject(MyPreference.loading, LoadingEntity.class);
        if (getLoading!=null && getLoading.size()>0) {
            for (LoadingEntity loadingEntity : getLoading) {
                int pos = isHave(loadingEntity.getName());
                if (pos>-1){
                    loadingEntities.get(pos).setCount(loadingEntities.get(pos).getCount()+1);
                }else {
                    LoadedEntity loading = new LoadedEntity();
                    loading.setName(loadingEntity.getName());
                    loading.setImgUrl(loadingEntity.getImgUrl());
                    loading.setFileDir(GlobalStr.getSDPath(context) + loadingEntity.getName() + "/" + "temp/");
                    loading.setCount(1);
                    loadingEntities.add(loading);
                }
            }
        }
        List<AlreadyLoadOkEntity> loadOkEntities = (List<AlreadyLoadOkEntity>) preference.getObject(MyPreference.loadok, AlreadyLoadOkEntity.class);
        if (loadOkEntities!=null && loadOkEntities.size()>0 && loadedEntities!=null && loadedEntities.size()>0){
            for (LoadedEntity loadedEntity:loadedEntities) {
                for (AlreadyLoadOkEntity loadOkEntity : loadOkEntities) {
                    if (loadOkEntity.getName().equals(loadedEntity.getName())){
                        loadedEntity.setImgUrl(loadOkEntity.getImgUrl());
                        break;
                    }
                }
            }
        }
        if (loadingEntities.size()>3 && loadedEntities.size()!=0){
            binding.recycleLoading.setVisibility(View.GONE);
            binding.ivLoading.setImageResource(R.drawable.up);
        }
        mHandler.sendEmptyMessage(0);
    }

    private int isHave(String name){
        for (int i=0;i<loadingEntities.size();i++){
            LoadedEntity loadedEntity = loadingEntities.get(i);
            if (loadedEntity.getName().equals(name)){
                return i;
            }
        }
        return -1;
    }

    private String isHaveLoadok(String name){
        String imgUrl="";
        List<AlreadyLoadOkEntity> loadOkEntities = (List<AlreadyLoadOkEntity>) preference.getObject(MyPreference.loadok, AlreadyLoadOkEntity.class);
        if (loadOkEntities==null || loadOkEntities.size()==0){
            return imgUrl;
        }
        for (AlreadyLoadOkEntity loadOkEntity:loadOkEntities){
            if (name.equals(loadOkEntity.getName())){
                imgUrl = loadOkEntity.getImgUrl();
                break;
            }
        }
        return imgUrl;
    }

    private String isHaveLoading(String name){
        String imgUrl="";
        List<LoadingEntity> loadOkEntities = (List<LoadingEntity>) preference.getObject(MyPreference.loading, LoadingEntity.class);
        if (loadOkEntities==null || loadOkEntities.size()==0){
            return imgUrl;
        }
        for (LoadingEntity loadOkEntity:loadOkEntities){
            if (name.equals(loadOkEntity.getName())){
                imgUrl = loadOkEntity.getImgUrl();
                break;
            }
        }
        return imgUrl;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void updata(DownLoadOkEvent event){
        if (event!=null){
            initData();
        }
    }

    @Subscribe
    public void fileData(DeleteFileEvent event){
        if (event!=null){
//            initData();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }
}
